import type { FormItemRule } from 'element-plus'

import type { RrsItem } from '../../type'
import { domainRules } from './domain'

type ChildError = {
  index: number
  key: string
}

export const useDomainAddRules = (props, fromRef, disabled = false) => {
  const isDisabledValue = inject('isDisabledValue', disabled)

  const childError = ref<ChildError[]>([])
  const rules = computed<Record<string, FormItemRule[]>>(() => ({
    domains: [...domainRules],
    rrsMain: [
      {
        trigger: 'blur',
        required: true,
        validator: () => {
          const rrs = unref(props).rrs as RrsItem[]

          if (isDisabledValue) {
            if (!rrs.some(v => v.name)) {
              childError.value = []
              // return new Error('请填写主机记录')
              return true
            }
          } else {
            if (rrs.length) {
              // 整体部分
              if (!rrs.some(v => v.value)) {
                childError.value = []
                return new Error('请填写解析记录')
              }
            }
          }
          return true
        }
      }
    ]
  }))

  provide('formRef', fromRef)
  provide('childError', childError)
  return { rules, childError }
}
